//
//  ViewController.m
//  qianke
//
//  Created by ZX on 2017/6/23.
//  Copyright © 2017年 ZX. All rights reserved.
//

#import "ViewController.h"
#import "myTableViewCell.h"
#import "ZXCustomerModel.h"
#import "choseRoleController.h"
#import "AddSaleActivityViewController.h"
#import "ZXSaleActivityController.h"
#import "ZXAddSaleActivityController.h"
#import "choseRoleController.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,NSURLSessionDataDelegate>
/*tableview*/
@property(strong ,nonatomic)UITableView * myTableView;
/*ilstArr*/
@property (weak, nonatomic) IBOutlet UIView *emptyView;
@property(copy ,nonatomic)NSMutableArray*listArr;
@property(assign ,nonatomic)BOOL isRefersh;
@property(assign ,nonatomic)int pageNo;
@property(copy ,nonatomic)NSString * Count;
@property(assign ,nonatomic)int pageSize;
@property(assign ,nonatomic)int upLoadNumber;
@property(assign ,nonatomic)BOOL NoMoreData;
@end

@implementation ViewController
@synthesize myTableView;
- (void)viewDidLoad {
    if (!_isLogin) {
        choseRoleController * vc = [choseRoleController new];
        [self.navigationController pushViewController:vc animated:NO];
    }
    [super viewDidLoad];
    _isRefersh = NO;
    _pageSize = 10;
    _pageNo = 2;
    NSLogfun;
    self.view.backgroundColor = baseBackgroundColor;
    [self layoutSubview];
    UIButton * btn =[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 90, 90)];
    btn.centerX = ScreenWidth/2;
    btn.centerY = ScreenHeight-60;
    btn.layer.cornerRadius = 45;
    btn.backgroundColor = [UIColor clearColor];
    [btn addTarget:self action:@selector(add_clack:) forControlEvents:UIControlEventTouchUpInside];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addCustomer) name:addcustomer object:nil];
    if (!_listArr) {
        _listArr =[[NSMutableArray alloc]init];
    }
    
    [self creatTableView];
    [self.view addSubview:btn];
    myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"刷新");
        my_AppDelegate.isShow = YES;
        _isRefersh = YES;
        [self loadData];
    }];
    myTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(toChoseClick2) name:@"ToChouseRole" object:nil];
}

#pragma mark --loaddata
//-(void)loadMoreData2222222222222{
//    if (_Count.intValue%_pageSize) {
//        _upLoadNumber = _Count.intValue/_pageSize + 1;
//    }else _upLoadNumber = _Count.intValue/_pageSize;
//    
//    NSString *strURL = [NSString stringWithFormat:@"%@%d/%d",ZXActivityChanceURL,_pageNo,_pageSize];
//    NSLog(@"strURL==%@",strURL);
//    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSURL *url = [NSURL URLWithString:strURL];
//    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
//    NSMutableURLRequest *mutableRequest = [request mutableCopy];
//    [mutableRequest addValue:my_AppDelegate.access_token forHTTPHeaderField:@"access_token"];
//    request = [mutableRequest copy];
//    if (_pageNo > _upLoadNumber) {
//        [myTableView.mj_footer setState:MJRefreshStateNoMoreData];
//        return;
//    }
//    NSLog(@"_pageNo==%d_upLoadNumber==%d",_pageNo,_upLoadNumber);
//    [HTTPHelper GetHeadmutableRequest:request success:^(NSDictionary *data) {
//        NSLog(@"%@",data);
//        NSLog(@"%@",[data objectForKey:@"message"]);
//        NSArray * arr = [data objectForKey:@"data"];
//        if (arr&&[arr isEqual:[NSNull null]]){
//            
//            for (NSDictionary * dic in arr) {
//                ZXCustomerModel * model = [ZXCustomerModel new];
//                [model setValuesForKeysWithDictionary:dic];
//                [_listArr addObject:model];
//            }
//            _pageNo++;
//            
//            NSLog(@"listArr.count==%lu",(unsigned long)_listArr.count);
//            
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [myTableView reloadData];
//            });
//            [myTableView.mj_footer endRefreshing];
//        }
//    } failure:^(NSError *error) {
//        [myTableView.mj_footer endRefreshing];
//        
//    }];
//}
-(void)loadMoreData{
    my_AppDelegate.isShow = YES;
    if (_Count.intValue%_pageSize) {
        _upLoadNumber = _Count.intValue/_pageSize + 1;
    }else _upLoadNumber = _Count.intValue/_pageSize;
    
    NSString *strURL = [NSString stringWithFormat:@"%@scrmForApp/ideaGuest/%d/%d?uid=%@&userName=%@",ZXBaseURL,_pageNo,_pageSize,my_AppDelegate.uid,my_AppDelegate.userName];
    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:strURL];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    [mutableRequest addValue:my_AppDelegate.access_token forHTTPHeaderField:accessTokenKey];
    request = [mutableRequest copy];
    if (_pageNo > _upLoadNumber) {
    }
    if (_NoMoreData) {
                [myTableView.mj_footer setState:MJRefreshStateNoMoreData];
                return;
    }
    NSLog(@"_pageNo==%d_upLoadNumber==%d",_pageNo,_upLoadNumber);
    [HTTPHelper GetHeadmutableRequest:request success:^(NSDictionary *data) {
        NSLog(@"%@",data);
        NSLog(@"%@",[data objectForKey:@"message"]);
        NSArray * arr = [data objectForKey:@"data"];
        NSString * msgCod = [data objectForKey:@"msgCod"];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (![msgCod isEqualToString:@"S0001"]) {
                _pageNo++;
            }else{
                _NoMoreData = YES;
                [myTableView.mj_footer endRefreshing];
                [myTableView.mj_footer setState:MJRefreshStateNoMoreData];
            }
        });
        
        if (arr&&![arr isEqual:[NSNull null]]) {
            for (NSDictionary * dic in arr) {
                ZXCustomerModel * model = [ZXCustomerModel new];
                [model setValuesForKeysWithDictionary:dic];
                [_listArr addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [myTableView reloadData];
            });
            [myTableView.mj_footer endRefreshing];
        }
        [myTableView.mj_footer endRefreshing];

        NSLog(@"listArr.count==%lu",(unsigned long)_listArr.count);
        
    } failure:^(NSError *error) {
        [myTableView.mj_footer endRefreshing];
        
    }];
}

-(void)loadData{
    myTableView.mj_footer.hidden = NO;
    NSString *strURL = [NSString stringWithFormat:@"%@scrmForApp/ideaGuest/1/10?uid=%@&userName=%@&searchType=ideaGuest",ZXBaseURL,my_AppDelegate.uid,my_AppDelegate.userName];
    NSLog(@"strURL====%@",strURL);
    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:strURL];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    [mutableRequest addValue:my_AppDelegate.access_token forHTTPHeaderField:accessTokenKey];
    request = [mutableRequest copy];
    
    [HTTPHelper GetHeadmutableRequest:request success:^(NSDictionary *data) {
        [_listArr removeAllObjects];
        NSLog(@"销售机会==%@",data);
        NSArray * arr = [data objectForKey:@"data"];
        if (arr&&![arr isEqual:[NSNull null]]) {
            _listArr = [ZXCustomerModel modelSformDics:arr];
            NSLog(@"销售机会数量==%ld",_listArr.count);
//            for (NSDictionary * dic in arr) {
//                ZXCustomerModel * model = [ZXCustomerModel new];
//                if (dic&&![dic isEqual:[NSNull null]]){
//                    [model setValuesForKeysWithDictionary:dic];
//                }
//                [_listArr addObject:model];
//            }
//            
            
//            for (NSDictionary * temDic in arr) {
//                ZXCustomerModel * model = [ZXCustomerModel modelSformDics:temDic];
//                [_listArr addObject:model];
//            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                _emptyView.hidden = YES;
                [myTableView reloadData];
                if (arr&&![arr isEqual:[NSNull null]]) {
                    if (arr.count<10) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            myTableView.mj_footer.hidden = YES;
                        });
                    }
                }
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                myTableView.mj_footer.hidden = YES;
            });
        }
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [myTableView reloadData];
            [myTableView.mj_header endRefreshing];
        });
    } failure:^(NSError *error) {
        [myTableView.mj_header endRefreshing];
    }];
    
}
-(void)loaddataTest{
    
    NSString *str = @"123456";
    
    NSString *result = [MD5Tool md5Str:str];
    
    NSLog(@"%@",result);
    
    NSString *str1 = [MD5Tool MD5ForLower16Bate:@"123456"];
    NSLog(@"小写16位:%@", str1);
    
    NSString *str2 = [MD5Tool MD5ForLower32Bate:@"123456"];
    NSLog(@"小写32位:%@", str2);
    
    NSString *str3 = [MD5Tool MD5ForUpper16Bate:@"123456"];
    NSLog(@"大写16位:%@", str3);
    
    NSString *str4 = [MD5Tool MD5ForUpper32Bate:@"123456"];
    NSLog(@"大写32位:%@", str4);
    
    NSString *strURL = [NSString stringWithFormat:@"%@1/%d",ZXActivityChanceURL,_pageSize];
    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:strURL];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    [mutableRequest addValue:my_AppDelegate.access_token forHTTPHeaderField:@"access_token"];
    request = [mutableRequest copy];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
                                                          delegate:self
                                                     delegateQueue:[[NSOperationQueue alloc] init]];
    
    // 创建任务(因为要使用代理方法,就不需要block方式的初始化了)
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
    
    // 启动任务
    [task resume];
   
}
// 1.接收到服务器的响应
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
    // 允许处理服务器的响应，才会继续接收服务器返回的数据
    NSLog(@"允许处理服务器的响应");
    completionHandler(NSURLSessionResponseAllow);
    NSLog(@"允许处理服务器的响应,才会继续接收服务器返回的数据");
}

// 2.接收到服务器的数据（可能调用多次）
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    // 处理每次接收的数据
    NSLog(@"处理每次接收的数据");
}

// 3.请求成功或者失败（如果失败，error有值）
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    // 请求完成,成功或者失败的处理
    NSLog(@"处理每次接收的数据");
}


#pragma mark --subviews
-(void)layoutSubview{
    // 设置viewController左上角的按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    //    button.frame = CGRectMake(0, 00, 80, 44);
    [button setImage:[UIImage imageNamed:@"whitenavback"] forState:UIControlStateNormal];
    [button setTitle:@"返回" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:13];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    //    [button addTarget:self action:@selector(backItemClick) forControlEvents:UIControlEventTouchUpInside];
    [button sizeToFit];
    // 相当于让按钮的内容往左边偏移20
    button.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}

-(void)viewWillAppear:(BOOL)animated{
    NSNumber *orientationUnknown = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
    [[UIDevice currentDevice] setValue:orientationUnknown forKey:@"orientation"];
    
    NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = NO;
}
-(void)viewDidAppear:(BOOL)animated{
    [self loadData];
    
}
-(void)viewWillDisappear:(BOOL)animated{
    my_AppDelegate.isShow = NO;
    self.navigationController.navigationBarHidden = NO;
}
#pragma mark --btnClick
-(void)addCustomer{
    ZXAddSaleActivityController *publish = [[ZXAddSaleActivityController alloc] init];
    [self.navigationController pushViewController:publish animated:NO];
    NSLog(@"添加客户");
}
- (IBAction)toChoseClick:(id)sender {
    choseRoleController * vc = [choseRoleController new];
    [self.navigationController pushViewController:vc animated:NO];

}
- (void)toChoseClick2{
    choseRoleController * vc = [choseRoleController new];
    [self.navigationController pushViewController:vc animated:NO];
    
}
- (void)add_clack:(id)sender {
    [[NSNotificationCenter defaultCenter]postNotificationName:@"wodeaddsaleactivity" object:nil];
}
#pragma mark --tableview datasouse
-(void)creatTableView{
    myTableView = [[UITableView alloc]initWithFrame:CGRectMake(ZXBigMargin, (88*heightScaleSize), ScreenWidth-2*ZXBigMargin, ScreenHeight-88*heightScaleSize-49) style:UITableViewStylePlain];
    myTableView.backgroundColor = [UIColor clearColor];
    myTableView.separatorStyle = NO;
    [self.view addSubview:myTableView];
    [myTableView registerNib:[UINib nibWithNibName:NSStringFromClass([myTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"cell"];
    myTableView.delegate = self;
    myTableView.dataSource = self;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _listArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    myTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    return cell;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell isKindOfClass:[myTableViewCell class]]) {
        myTableViewCell *displayCell = (myTableViewCell *)cell;
        ZXCustomerModel * model = _listArr[indexPath.row];
        displayCell.status = model;
        displayCell.layer.cornerRadius = 5;
//        NSLog(@"displayCell.noticeId = %@",displayCell.noticeId);
        }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZXCustomerModel * model = _listArr[indexPath.row];
    int height1 = [model.address stringSizeWithMaxSize:CGSizeMake(ScreenWidth*2/3, ScreenHeight) withFont:textfont].height;
    return 140 +height1;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    myTableViewCell * cell =[tableView cellForRowAtIndexPath:indexPath];
    cell.userInteractionEnabled = NO;
//    if (cell.activityCount.intValue){
        ZXSaleActivityController * saleVc = [ZXSaleActivityController new];
        saleVc.chanceId = cell.noticeId;
        saleVc.title = @"销售活动";
        saleVc.view.backgroundColor = baseBackgroundColor;
        [self.navigationController pushViewController:saleVc animated:YES];
//    }else{
//        AddSaleActivityViewController * saleVc = [AddSaleActivityViewController new];
//        saleVc.chanceId = cell.noticeId;
//        saleVc.title = @"添加销售活动";
//        saleVc.view.backgroundColor = baseBackgroundColor;
//        [self.navigationController pushViewController:saleVc animated:YES];
//    }
    cell.userInteractionEnabled = YES;
}
#pragma mark -- StatusBar

//设置样式
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

//设置是否隐藏
- (BOOL)prefersStatusBarHidden {
    return NO;
}

//设置隐藏动画
- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationNone;
}
//是否可以旋转
- (BOOL)shouldAutorotate
{
    return NO;
}
//支持的方向
-(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
